/*
*JavaFinder.  This creates and array of all of the files of a specific type in a given dir.
*Some of the code was taken from: http://www.exampledepot.com/
*@author T. Codi Gann
*/

import java.io.File;
import java.io.FilenameFilter;


public class Finder{
	
	private char slash='\\';
	private String srcDir;	
	private String pathList[];
	private String filter;

	/**
	*This is the constructor....in case you wanted to know :P
	*/
	Finder(String path, String filter){
		pathList = new String[0];
		srcDir = path;		
		this.filter = filter;
	}
	
	//returns an array of all the class files
	public String[] getFiles(){return pathList;}
	
	/**
	*Starts the process of visiting each directory
	*
	*/
	public void runVisit(){
		File dir = new File(srcDir);
		visitAllDirs(dir);
	}
	
	/**
	*
	*prints the list of java files
	*/
	public void printList(){
		System.out.println("Path List: " + pathList.length);
		for (int i=0; i<pathList.length; i++) {
		        System.out.println(pathList[i]);
		}
	}

	/** 
	*Recursively processes only directories under the given source dir
	*calls process, which searches each directory for java files
	*/
	private void visitAllDirs(File dir) {
		if (dir.exists() && dir.isDirectory()) {
			process(dir);
			String[] children = dir.list();
		    for (int i=0; i<children.length; i++) {
		        visitAllDirs(new File(dir, children[i]));
		    }
		}
	}//end visit
	
	/**
	*Searches each directory the specific files.  If they are found
	*they are added to the array.
	*
	*/
	private void process (File dir){
		String oldArray [], newFiles[];
		FilenameFilter filter = new Filter(this.filter);
		String children[] = dir.list(filter);
		/*There are the ones we want here*/
		if (children != null){
			
			for (int i=0; i<children.length; i++)
				children[i] = dir.getPath() + slash + children[i];
						
			if (pathList.length == 0){
				pathList =  children;
			}else
			{
				newFiles = children;	
				oldArray = pathList;
				
				pathList = new String[pathList.length + newFiles.length];
				
				int i;
				for(i=0; i<oldArray.length; i++)
					pathList[i] = oldArray[i];
				for(int j = 0; i<pathList.length; j++){
					pathList[i] = newFiles[j];
					i++;
				}
			}	
		}	
	
	} //end process
	
}//end FileViewer

/*
*Implements FilenameFilter.  This ensures that only files
*that end in ".java" are processed
*/
class Filter implements FilenameFilter {
	private String filter;
	
	Filter (String filter){
		this.filter= filter;
	}
    public boolean accept(File dir, String name) {
        return (name.endsWith(filter));
    }
}

